using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Doppler.Core.Plugin;
using Doppler.Core;
using Doppler.Resources;

namespace Doppler.Gui {
  public partial class OptionsForm : Form {
    /// <summary>
    /// Initializes a new instance of the <see cref="OptionsForm"/> class.
    /// </summary>
    public OptionsForm ( ) {
      // sets the icon to the the icon in the resources
      this.Icon = ResourceHelper.GetObject<Icon> ( "doppler" );
      InitializeComponent ( );

      optionsTree.BeforeSelect += new TreeViewCancelEventHandler ( optionsTree_BeforeSelect );
      InitializePluginOptions ( );
      this.ok.Text = ResourceHelper.GetString ( this.ok.Text );
      this.cancel.Text = ResourceHelper.GetString ( this.cancel.Text );
      this.Text = ResourceHelper.GetString ( "Doppler.Gui.OptionsForm.Text" );
    }

    /// <summary>
    /// Initializes the plugin options.
    /// </summary>
    private void InitializePluginOptions ( ) {
      TreeNode tn = optionsTree.Nodes.Add ( ResourceHelper.GetString ( "Doppler.Gui.OptionsForm.Tree.PluginNodeText" ) );
      foreach ( IPlugin plugin in Doppler.Core.PluginHelper.PluginFactory.Plugins ) {
        if ( plugin.HasUserOptions ) {
          TreeNode ptn = new TreeNode ( plugin.ProductName );
          ptn.Tag = plugin.Guid;
          tn.Nodes.Add ( ptn );
        }
      }
    }

    /// <summary>
    /// Handles the BeforeSelect event of the optionsTree control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.Forms.TreeViewCancelEventArgs"/> instance containing the event data.</param>
    void optionsTree_BeforeSelect ( object sender, TreeViewCancelEventArgs e ) {
      if ( e.Node != null && e.Node.Tag != null && e.Node.Tag.GetType ( ) == typeof ( Guid ) ) {
        IPlugin plug = PluginHelper.PluginFactory.Find ( ( Guid ) e.Node.Tag );
        if ( plug != null ) {
          this.DisplayPluginOptions ( plug );
        }
      } else {
        this.splitContainer.Panel2.Controls.Clear ( );
      }
    }

    /// <summary>
    /// Displays the plugin options.
    /// </summary>
    /// <param name="plugin">The plugin.</param>
    private void DisplayPluginOptions ( IPlugin plugin ) {
      plugin.OnOptionsOpen ( );
      this.DisplayOptionsPanel ( plugin.Options );
    }

    /// <summary>
    /// Displays the options panel.
    /// </summary>
    /// <param name="panel">The panel.</param>
    private void DisplayOptionsPanel ( Panel panel ) {
      this.splitContainer.Panel2.Controls.Clear ( );
      panel.AutoScroll = true;
      panel.Dock = DockStyle.Fill;
      this.splitContainer.Panel2.Controls.Add ( panel );
    }
  }
}